/*
 *  Copyright 2008-2010 www.jrails.org
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.rails.extjs.javascript;

import java.util.ArrayList;
import java.util.List;

import org.rails.extjs.AbsBase;
import org.rails.extjs.javascript.Function;
import org.rails.extjs.javascript.JavaScript;
import org.rails.extjs.json.Json;

public class DelayedTask extends AbsBase {
	
	protected List<Object> args = new ArrayList<Object>();
	
	private String id;
	private int delay;
	private Function run;

	public DelayedTask(int delay,Function run) {
		super();
		this.delay = delay;
		this.run = run;
		setId(createId());
	}
	
	public DelayedTask(int delay,String id,Function run) {
		super();
		this.delay = delay;
		this.run = run;
		setId(id);
	}

	public void addArg(Object arg){
		args.add(arg);
	}
	
	public void insertArg(int index,Object arg){
		args.add(index, arg);
	}
	
	public void removeArg(int index){
		args.remove(index);
	}
	
	public Object getArg(int index){
		return args.get(index);
	}
	
	public void clearArgs(){
		args.clear();
	}
	
	public void setArgs(List<Object> args){
		this.args = args;
	}
	
	public List<Object> getArgs(){
		return args;
	}
	
	public void setId(String id){
		this.id = id;
	}
	
	public String getId(){
		return id;
	}
	
	public static JavaScript cancel(String taskId){
		return new JavaScript("{0}.cancel();",taskId);
	}
	
	public JavaScript cancel(){
		return new JavaScript("{0}.cancel();",getId());
	}

	@Override
	public String getScript() {
		script = new StringBuffer("");
		script.append("var " + id);
		script.append(format("=new Ext.util.DelayedTask({0},this,{1});",run.getScript(),Json.escape(args)));
		script.append(format("{0}.delay({1});",this.getId(),delay));
		return script.toString();
	}
}
